package com.action.gulimall.coupen.service.impl;

import com.action.gulimall.coupen.entity.SeckillSkuRelationEntity;
import com.action.gulimall.coupen.service.SeckillSkuRelationService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.action.common.utils.PageUtils;
import com.action.common.utils.Query;

import com.action.gulimall.coupen.dao.SeckillSessionDao;
import com.action.gulimall.coupen.entity.SeckillSessionEntity;
import com.action.gulimall.coupen.service.SeckillSessionService;


@Service("seckillSessionService")
public class SeckillSessionServiceImpl extends ServiceImpl<SeckillSessionDao, SeckillSessionEntity> implements SeckillSessionService {

    @Autowired
    SeckillSkuRelationService seckillSkuRelationService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<SeckillSessionEntity> page = this.page(
                new Query<SeckillSessionEntity>().getPage(params),
                new QueryWrapper<SeckillSessionEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public List<SeckillSessionEntity> getLates3DaySession() {
        LocalDate startDate = LocalDate.now();
        LocalDate endDate = startDate.plusDays(3);
        List<SeckillSessionEntity> seckillSessionEntities = this.list(new QueryWrapper<SeckillSessionEntity>().gt("start_time", startDate).or().lt("end_time", endDate));
        Map<Long, SeckillSessionEntity> seckillSessionEntityMap = seckillSessionEntities.stream().collect(
                Collectors.toMap(s -> s.getId(),s -> {
                    s.setRelationSkus(new ArrayList<>());
                    return s;
                }));
        List<SeckillSkuRelationEntity> seckillSkuRelationEntities = seckillSkuRelationService.getBySessionIds(seckillSessionEntityMap.keySet());
        seckillSkuRelationEntities.forEach(e -> {
            SeckillSessionEntity seckillSessionEntity = seckillSessionEntityMap.get(e.getPromotionSessionId());
            seckillSessionEntity.getRelationSkus().add(e);
        });
        return seckillSessionEntities;
    }

}